package com.hereway.core.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

import com.hereway.core.model.DBColumnModel;
import com.hereway.core.model.DBTableModel;

public class PDMParser {

	private String filepath = "";
	// 表名-列集合对象
	private HashMap<String, List<DBColumnModel>> tab_colHs = new HashMap<String, List<DBColumnModel>>();

	public PDMParser(String pdmpath) {
		filepath = pdmpath;
	}

	/**
	 * 获取表集合
	 * @return
	 */
	public List<DBTableModel> getTableList() {

		List<DBTableModel> tbs = new ArrayList<DBTableModel>();

		List<Element> elementLs = new ArrayList<Element>();
		try {
			elementLs = createXMLElement();
		} catch (Exception e) {
			System.out.println("获取数据失败");
			e.printStackTrace();
			return null;
		}

		// 得到tables对象，该对象是该pdm文件中所有表的集合
		for (Element element : elementLs) {
			for (Iterator<Element> iter = element.elementIterator("Table"); iter.hasNext();) {
				Element tableElent = iter.next();
				// 表对象
				DBTableModel tableModel = new DBTableModel();
				tableModel.setTableCode(tableElent.elementText("Code"));
				tableModel.setTableName(tableElent.elementText("Name"));
				tableModel.setDesc(tableElent.elementText("Comment"));
				createColums(tableElent);

				tbs.add(tableModel);
			}
		}
		return tbs;
	}

	/**
	 * 创建表-列集合对象
	 * 
	 * @param tableElent
	 */
	private void createColums(Element tableElent) {
		// 通过一个table对象，得到columns对象
		Element columns = tableElent.element("Columns");
		int order = 1;
		for (Iterator<Element> cols = columns.elementIterator("Column"); cols.hasNext();) {
			Element column = cols.next();

			DBColumnModel columnModel = new DBColumnModel();
			column.elements();
			columnModel.setTableName(tableElent.elementText("Code"));
			columnModel.setColCode(column.elementText("Code"));
			columnModel.setColName(column.elementText("Name"));
			columnModel.setColOrder(order);
			columnModel.setDataType(column.elementText("DataType"));

			String pkId = column.attributeValue("Id");
			String keys_key_id = tableElent.element("Keys").element("Key").attributeValue("Id");

			String keys_key_column_column_ref = tableElent.element("Keys").element("Key").element("Key.Columns")
					.element("Column").attributeValue("Ref");
			String keys_primarykey_ref_id = tableElent.element("PrimaryKey").element("Key").attributeValue("Ref");

			if (keys_primarykey_ref_id.equals(keys_key_id) && keys_key_column_column_ref.equals(pkId)) {
				columnModel.setIsPk(true);
				columnModel.setIsNullable(false);
			} else {
				columnModel.setIsNullable(true);
			}

			columnModel.setDataLen(column.elementText("Length") == null ? 0 : Integer.parseInt(column
					.elementText("Length")));
			columnModel.setDataPrecision(column.elementText("Precision") == null ? 0 : Integer.parseInt(column
					.elementText("Precision")));
			columnModel.setDesc(column.elementText("Comment"));

			List<DBColumnModel> columnModelTemp = new ArrayList<DBColumnModel>();
			if (tab_colHs.containsKey(tableElent.elementText("Code"))) {
				columnModelTemp = tab_colHs.get(tableElent.elementText("Code"));
			}
			columnModelTemp.add(columnModel);

			tab_colHs.put(tableElent.elementText("Code"), columnModelTemp);
			order++;
		}
	}

	/**
	 * 读取文件并构造中间数据
	 * 
	 * @return
	 * @throws Exception
	 */
	private List<Element> createXMLElement() throws Exception {

		File file = new File(filepath);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(file);
		// 创建表对象的段落标记
		XPath path = doc.createXPath("//c:Tables");

		List<Element> elementLs = path.selectNodes(doc);
		return elementLs;
	}

	/**
	 * 表code->列对象
	 * 
	 * @param DBTableModel
	 * @return
	 */
	public List<DBColumnModel> getColumnList(String tabCode) {

		List<DBColumnModel> columnModelLs = tab_colHs.get(tabCode);

		return columnModelLs;
	}

	public static void main(String[] args) {
		PDMParser pdmEntry = new PDMParser("D:\\Project\\DM\\trunk\\db\\dm.pdm");
		List<DBTableModel> tabLs = pdmEntry.getTableList();
		List<DBColumnModel> columnModel = pdmEntry.getColumnList(tabLs.get(0).getTableCode());
	}
}
